﻿using System.Threading;
using System.Windows.Forms;
using ThreadSyncron.UI;
using ThreadSyncron.Utils;
using ThreadSyncron.Utils.Utils.Interfaces;

namespace ThreadSyncron.ApplicationContext
{
    public class AppContext : System.Windows.Forms.ApplicationContext
    {
        public FMain form;

        SynchronizationContext context;

        public AppContext()
        {
            form = new FMain();
            form.Visible = false;
            form.FormClosed += (sender, e) => ExitThread();

            if (SynchronizationContext.Current != null)
            {
                context = SynchronizationContext.Current;
            }
            else
            {
                context = new SynchronizationContext();
                SynchronizationContext.SetSynchronizationContext(context);
            }

        }

        public void Run()
        {
            if (MessageBox.Show("Start?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                string threaName = (TSPool.Instance.GetThreadsCount() + 1).ToString();
                Parrams pars = new Parrams();
                pars.AddParam("Test string " + threaName);
                TSPool.Instance.AddThread(MakeAction, threaName, this.EndAction, pars);
                Application.Run(this);
            }
            else
            {
                this.ExitThreadCore();
            }
        }

        private void EndAction(IIOActionParameters inparams)
        {
            context.Send(new SendOrPostCallback(ShowForm), null);       
        }

        private IIOActionParameters MakeAction(IIOActionParameters inparams)
        {
            string s = inparams.GetParam(0) as string;
            if (s == null) return null;
            Parrams outPars = new Parrams();
            outPars.AddParam(string.Format("Thread {0} returned", s));
            Thread.Sleep(5500); 
            return outPars;
        }

        public void ShowForm(object state)
        {
            form.Show();
        }


    }
}
